﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace CodeCounsel.SharePoint.Flash
{
    public class WebAppReceiver
        : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            // change config
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
            SPWebConfigModification modification = CreateModification(properties);
            webApp.WebConfigModifications.Add(modification);
            webApp.Update();
            webApp.WebService.ApplyWebConfigModifications();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            // unchange config
            SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
            SPWebConfigModification modification = CreateModification(properties);
            webApp.WebConfigModifications.Remove(modification);
            webApp.Update();
            webApp.WebService.ApplyWebConfigModifications();
        }

        private static SPWebConfigModification CreateModification(SPFeatureReceiverProperties properties)
        {
            SPWebConfigModification modification = new SPWebConfigModification();
            modification.Name = "add[@type='CodeCounsel.SharePoint.Flash.FlvHandler, CodeCounsel.SharePoint.Flash, Culture=neutral, Version=1.0.0.0, PublicKeyToken=a83cc8fa1cb070d9'][@path='*.flv'][@verb='GET,HEAD,POST,DEBUG']";
            modification.Path = "configuration/system.web/httpHandlers";
            modification.Owner = "CCFlash";
            modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            modification.Value = @"<add path=""*.flv"" type=""CodeCounsel.SharePoint.Flash.FlvHandler, CodeCounsel.SharePoint.Flash, Culture=neutral, Version=1.0.0.0, PublicKeyToken=a83cc8fa1cb070d9"" verb=""GET,HEAD,POST,DEBUG"" />";
            return modification;
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        { }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        { }
    }
}
